<script setup>
import { ref } from "vue";
const props = defineProps({
  showCancelBtn: {
    type: Boolean,
    default: false
  },
  showConfirmBtn: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: ""
  },
  type: {
    type: String,
    default: "text"
  },
  maxlength: {
    type: [Number, String],
    default: 100
  },
  disabled: {
    type: Boolean,
    default: false
  },
  autofocus: {
    type: Boolean,
    default: false
  },
  confirmType: {
    type: String,
    default: "search"
  }
});

const emit = defineEmits(["cancel", "confirm", "clear", "input", "blur", "focus", "update:modelValue", "searchBarClick"]);

const keyword = ref("");

const cancel = () => {
  emit("cancel");
};
const confirm = () => {
  emit("confirm", keyword.value);
};
const clear = () => {
  keyword.value = "";
  emit("clear", keyword.value);
  emit("update:modelValue", keyword.value);
};
const input = e => {
  keyword.value = e.detail.value;
  emit("input", keyword.value);
  emit("update:modelValue", keyword.value);
};
const blur = () => {
  emit("blur", keyword.value);
};
const focus = () => {
  emit("focus", keyword.value);
};
const searchBarClick = () => {
  emit("searchBarClick", keyword.value);
};
</script>

<template>
<view class="uni-search-bar" @click="searchBarClick">
  <view class="search-bar-left"></view>
  <view class="search-bar-center position-relative">
    <text class="fa fa-search"></text>
    <input class="search-input"
           v-model="keyword"
           :type="type"
           :placeholder="placeholder"
           :maxlength="maxlength"
           :disabled="disabled"
           :confirm-type="confirmType"
           :focus="autofocus"
           @input="input"
           @confirm="confirm"
           @blur="blur"
           @focus="focus"
    />
    <view v-if="keyword" @click="clear">
      <text class="fa fa-plus-circle"></text>
    </view>
    <view v-if="disabled" class="w-full h-full position-absolute top-0 left-0"></view>
  </view>
  <view v-if="showCancelBtn || showConfirmBtn" class="search-bar-right">
    <view v-if="showCancelBtn" class="search-bar-cancel" @click="cancel">
      取消
    </view>
    <view v-if="showConfirmBtn" class="search-bar-confirm" @click="confirm">
      确定
    </view>
  </view>
</view>
</template>